import React, {Component} from 'react';
import {
  Card,
  List,
  Button,
  Divider,
  Row,
  Col,
  Icon,
  Upload,
  Form,
  Input,
  Tooltip,
  message,
} from 'antd';

import styles from './index.less';
import {Link} from 'react-router-dom';
import PageHeader from 'ant-design-pro/lib/PageHeader';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import AvatarUpload from './component/avatarUploader';
const ButtonGroup = Button.Group,
  {Description} = DescriptionList;

const Dragger = Upload.Dragger;
const FormItem = Form.Item;

let configMapList = {
  genre: '级别',
  engine: '发动机',
  marketTime: '上市时间',
  manufacturerPrice:'厂商指导价',
  gearBox: '变速箱',
  size: '长*宽*高（mm）',
  bodyWork: '车身结构',
  maxSpeed: '最高车速（km/h）',
  officialAcceleration: '官方0-100km/h加速（s）',
  measuredAcceleration: '实测0-100km/h加速（s）',
  measuredBraking: '实测100-0km/h制动（m）',
  measuredFuelConsumption: '实测油耗（L/100km)',
  fuelConsumption: '工信部综合油耗',
  groundClearance: '实测离地间隙（mm）',
  qualityAssurance: '整车质保',
  wheelbase: '轴距（mm）',
  frontTrack: '前轮距（mm）',
  rearTrack: '后轮距（mm）',
  miniGroundClearance: '最小离地间隙（mm）',
  allWeight: '整备质量（kg）',
  tankVolume: '油箱容积（L）',
  luggageVolume: '行李厢容积（L）',
  engineType: '发动机型号',
  displacementML: '排量（mL）',
  displacementL: '排量（L）',
  inlet: '进气形式',
  cylinderArrangement: '气缸排列形式',
  cylinderNum: '气缸数（个）',
  cylinderValves: '每缸气门数（个）',
  reductionRatio: '压缩比例',
  valveTrain: '配气机构',
  bore: '缸径（mm）',
  pistonTravel: '行程（mm）',
  maxHorsepower: '最大马力（Ps）',
  maxPower: '最大功率（kW）',
  maxPowerspeed: '最大功率转速（rpm）',
  maxTorque: '最大扭矩（N`m）',
  maxTorquespeed: '最大扭矩转速（rpm）',
  engineSpecialtech: '发动机特有技术',
  fuelForm: '燃料形式',
  fuelMark: '燃油标号',
  fuelSupply: '供油方式',
  cylinderHeadmaterial: '缸盖材料',
  cylinderBlockmaterial: '缸体材料',
  environmentalStandard: '环保标准',
  shiftNum: '档位个数',
  gearboxType: '变速箱类型',
  drivingMode: '驱动方式',
  fourwheelDrive: '四驱形式',
  centralDifferential: '中央差速器结构',
  frontSuspension: '前悬架类型',
  rearSuspension: '后悬架类型',
  powerType: '助力类型',
  bodyStructure: '车体结构',
  frontBrake: '前制动器类型',
  rearBrake: '后制动器类型',
  parkingType: '驻车制动类型',
  frontTire: '前轮胎规格',
  rearTire: '后轮胎规格',
  spareTire: '备胎规格',
  abs: 'ABS防抱死',
  brakeDistribution: '制动力分配（EBD/CBC等）',
  brakeAssist: '刹车辅助（EBA/BAS/BA等）',
  tractionControl: '牵引力控制（ASR/TCS/TRC等）',
  stabilityControl: '车身稳定控制（ESC/ESP/DSC等）',
  variableSuspension: '可变悬架',
  airSuspension: '空气悬架',
  electroSuspension: '电磁感应悬架',
  variableSteeringratio: '可变转向比',
  frontDifferentiallock: '前桥限滑差速器/差速锁',
  centralDifferentiallock: '中央差速器锁止功能',
  rearDifferentiallock: '后桥限滑差速器/差速锁',
};

import Fetch from '../../../common/fetch';
import myaxios, {get, put, post, deleteAxios} from 'common/fetch';

class ConfigItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowInput: false,
      value: '',
    };
  }
  componentDidMount() {
    this.setState({
      value: this.props.value,
    });
  }
  handleClick = () => {
    this.setState({
      isShowInput: true,
    });
  };
  handleEnter = () => {
    const {onEnter} = this.props;
    const {value} = this.state;
    this.setState({
      isShowInput: false,
    });
    onEnter && onEnter(value);
  };
  handleBlur = () => {
    const {onEnter} = this.props;
    const {value} = this.state;
    this.setState({
      isShowInput: false,
    });
    onEnter && onEnter(value);
  };
  handleChange = event => {
    this.setState({
      value: event.target.value,
    });
  };
  render() {
    const {title} = this.props;
    const {isShowInput, value} = this.state;
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 20},
      },
    };
    return (
      <FormItem label={title} {...formItemLayout}>
        {isShowInput ? (
          <Input
            autoFocus
            placeholder={title}
            defaultValue={value}
            onPressEnter={this.handleEnter}
            onBlur={this.handleBlur}
            onChange={this.handleChange}
          />
        ) : (
          <div className={styles.carItem} onClick={this.handleClick}>
            {value}
          </div>
        )}
      </FormItem>
    );
  }
}

class CarConfig extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modelId: '',
      editable: false,
      specDetail: {},
      config: [],
    };
  }
  componentDidMount() {
    const {match} = this.props;
    get(`/nnc/vehicle/spec/${match.params.specId}`, {}).then(res => {
      let configArray = [];
      for (let propItem in res) {
        if (configMapList[propItem]) {
          let configArrayItem = {};
          configArrayItem['name'] = configMapList[propItem];
          configArrayItem['key'] = propItem;
          configArrayItem['value'] = res[propItem] ? res[propItem] : '--';
          configArray.push(configArrayItem);
        }
      }
      this.setState({
        config: configArray,
        specDetail: res,
      });
    });
  }
  // 编辑条目
  editItem = (key, value) => {
    let {match} = this.props;
    return put(`/nnc/vehicle/spec/${match.params.specId}`, {
      [key]: value,
    }).then(res => {
      message.success('编辑成功');
    });
  };
  renderConfigList() {
    let {configList} = this.state;
    return configList.map(item => {
      return <Description term={item.name}>{item.value}</Description>;
    });
  }
  render() {
    const {config, specDetail} = this.state;
    const {match} = this.props;
    return (
      <div>
        <PageHeader
          title={
            specDetail.brandName +
            '/' +
            specDetail.modelName +
            '/' +
            specDetail.name
          }
          breadcrumbList={[
            {
              title: '车库',
              href: '/vehicle',
            },
            {
              title: '型号列表',
              href: `/vehicle/model/${match.params.modelId}`,
            },
            {
              title: '车辆配置信息',
            },
          ]}
          linkElement={Link}
          className={styles.pageHeader}
        />
        <div className={`${styles.content} ${styles['home-container']}`}>
          <Card title="配置详情" style={{margin: 24}} bordered={false}>
            <Row>
              <AvatarUpload onEdit={(value)=>{return this.editItem('specImg',value)}} defaultImg={specDetail.img}/>
            </Row>
            <Divider />
            <Form>
              {config.map((item, index) => (
                <ConfigItem
                  key={index}
                  title={item.name}
                  value={item.value}
                  onEnter={value => {
                    if (item.value != value) {
                      this.editItem(item.key, value);
                    }
                  }}
                />
              ))}
            </Form>
          </Card>
        </div>
      </div>
    );
  }
}

export default CarConfig;
